#!/bin/bash
REVISION="${1}"
COMPRESS="gzip"
WORKDIR="kodi-${REVISION}"

if [[ -z "${REVISION}" ]]; then echo "Usage: ${0} tag|branch|commit [gzip|xz|...]" && exit 1; fi
if [[ -d "${WORKDIR}" ]]; then echo "${WORKDIR} dir exists, refusing to overwrite" && exit 1; fi
if [[ -n "${2}" ]]; then COMPRESS="${2}"; fi

which git >/dev/null || exit 1
git rev-list -1 ${REVISION} >/dev/null || exit 1

mkdir -p "${WORKDIR}"
GIT_WORK_TREE="${WORKDIR}" git checkout "${REVISION}" -- . || exit 1

pushd "${WORKDIR}" >/dev/null
./bootstrap || ( rm -rf "${WORKDIR}" && exit 1 )
popd >/dev/null

pushd "${WORKDIR}/tools/android/depends" >/dev/null
./bootstrap || ( rm -rf "${WORKDIR}" && exit 1 )
popd >/dev/null

echo "${REVISION}" > "${WORKDIR}"/VERSION
echo "`git rev-list -1 ${REVISION}`" >> "${WORKDIR}"/VERSION

tar cf "${WORKDIR}.tar" "${WORKDIR}" || ( rm -f "${WORKDIR}.tar" && rm -rf "${WORKDIR}" exit 1 )
${COMPRESS} ${WORKDIR}.tar || ( rm -f "${WORKDIR}.tar" && rm -rf "${WORKDIR}" && exit 1 )

rm -rf ${WORKDIR}
exit 0
